package com.jianan.mis.app.overseastudy;

import static com.jianan.mis.util.ui.calendar.SWTCalendarWrapper.openCalendar;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.dozer.util.mapping.DozerBeanMapper;

import org.apache.commons.lang.math.NumberUtils;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.jianan.mis.data.domain.Country;
import com.jianan.mis.data.domain.Employee;
import com.jianan.mis.data.domain.Interman;
import com.jianan.mis.data.domain.OsConsultation;
import com.jianan.mis.data.domain.OsConsultationState;
import com.jianan.mis.data.domain.OsContract;
import com.jianan.mis.data.domain.OsContractState;
import com.jianan.mis.service.OsConsultationService;
import com.jianan.mis.service.OsContractService;
import com.jianan.mis.service.OsDepartmentContractService;
import com.jianan.mis.sys.IMessageKeys;
import com.jianan.mis.sys.ResourceManager;
import com.jianan.mis.sys.SpringBeanFactory;
import com.jianan.mis.util.StringUtils;

public class OsSignConfirmDialog extends Dialog {

	private Text txtCommuTranslateSum;
	private OsConsultation osConsultation;
	
	private Text txtContractNo;
	private Text txtSignSum;
	private Text txtSignDate;

	final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
	
	/**
	 * Create the dialog
	 * @param parentShell
	 */
	public OsSignConfirmDialog(Shell parentShell) {
		super(parentShell);
	}

	/**
	 * Create contents of the dialog
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		Composite container = (Composite) super.createDialogArea(parent);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.marginTop = 20;
		gridLayout.marginLeft = 20;
		gridLayout.numColumns = 2;
		container.setLayout(gridLayout);

		final Label label_1 = new Label(container, SWT.NONE);
		label_1.setFont(ResourceManager.getFont("", 10, SWT.BOLD));
		label_1.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
		label_1.setText("签约信息:");

		final Label label = new Label(container, SWT.NONE);
		label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label.setText("签约日期:");

		txtSignDate = new Text(container, SWT.BORDER);
		txtSignDate.addMouseListener(new MouseAdapter() {
			public void mouseDown(final MouseEvent e) {
				openCalendar(e, txtSignDate, dateFormat);
			}
		});
		final GridData gd_txtSignDate = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtSignDate.widthHint = 87;
		txtSignDate.setLayoutData(gd_txtSignDate);
		txtSignDate.setText(dateFormat.format(new Date()));

		final Label label_4 = new Label(container, SWT.NONE);
		label_4.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_4.setText("通讯翻译费:");

		txtCommuTranslateSum = new Text(container, SWT.BORDER);
		final GridData gd_txtCommuTranslateSum = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtCommuTranslateSum.widthHint = 100;
		txtCommuTranslateSum.setLayoutData(gd_txtCommuTranslateSum);

		final Label label_2 = new Label(container, SWT.NONE);
		label_2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_2.setText("签约金额:");

		txtSignSum = new Text(container, SWT.BORDER);
		final GridData gd_txtSignSum = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtSignSum.widthHint = 100;
		txtSignSum.setLayoutData(gd_txtSignSum);

		final Label label_3 = new Label(container, SWT.NONE);
		label_3.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_3.setText("合同号:");

		txtContractNo = new Text(container, SWT.BORDER);
		final GridData gd_txtContractNo = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtContractNo.widthHint = 224;
		txtContractNo.setLayoutData(gd_txtContractNo);
		//
		return container;
	}
	
	public void setOsConsultation(OsConsultation osConsultation) {
		this.osConsultation = osConsultation;
	}

	private OsContractService osContractService = (OsContractService) SpringBeanFactory
			.getBean("osContractService");

	private OsDepartmentContractService osDepartmentContractService = (OsDepartmentContractService) SpringBeanFactory
			.getBean("osDepartmentContractService");
	
	private boolean checkInfo() {
		if (StringUtils.isEmpty(txtSignDate.getText())) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"请输入签约日期!");
			txtSignDate.setFocus();
			return false;
		}
		if(StringUtils.isNotEmpty(txtCommuTranslateSum.getText())
				&& !NumberUtils.isNumber(txtCommuTranslateSum.getText())) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"通讯翻译费输入不正确，请重新输入!");
			txtCommuTranslateSum.setFocus();
			return false;
		}
		if (StringUtils.isEmpty(txtSignSum.getText())) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"请输入签约金额!");
			txtSignSum.setFocus();
			return false;
		}
		if (!NumberUtils.isNumber(txtSignSum.getText())) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"签约金额输入错误，请重新输入!");
			txtSignSum.setFocus();
			return false;
		}
		if (new BigDecimal(txtSignSum.getText()).compareTo(new BigDecimal(0)) <= 0) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"签约金额应大于0，请重新输入!");
			txtSignSum.setFocus();
			return false;
		}
		if (StringUtils.isEmpty(txtContractNo.getText())) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"请输入合同号!");
			txtContractNo.setFocus();
			return false;
		}
		if (haveSpecialChar(txtContractNo.getText())) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"合同号只包含字母及数字，请重新输入!");
			txtContractNo.setFocus();
			return false;
		}
		if (txtContractNo.getText().length() != 10) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"合同号长度应为10，请重新输入!");
			txtContractNo.setFocus();
			return false;
		}
		if (osDepartmentContractService.checkContractNoExists(txtContractNo.getText())
				|| osContractService.checkContractNoExists(txtContractNo.getText())) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"合同号重复，请重新输入!");
			txtContractNo.setFocus();
			return false;
		}
		return true;
	}
	
	private boolean haveSpecialChar(String str) {
		for(char c : str.toCharArray()) {
			System.out.println(c);
			if (c < 48)
				return true;
			if (c > 57 && c < 65)
				return true;
			if (c > 90 && c < 97)
				return true;
			if (c > 122)
				return true;
		}
		return false;
	}

	/**
	 * Create contents of the button bar
	 * @param parent
	 */
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,
				true);
		createButton(parent, IDialogConstants.CANCEL_ID,
				IDialogConstants.CANCEL_LABEL, false);
	}

	/**
	 * Return the initial size of the dialog
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(434, 234);
	}
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("签约确认");
	}
	protected void buttonPressed(int buttonId) {
		if (buttonId == IDialogConstants.OK_ID) {
			if (checkInfo()) {
				if (MessageDialog.openConfirm(getShell(), 
						IMessageKeys.CONFIRM, "确认签约吗?")) {
					try {
						OsContract osContract = new OsContract();
						DozerBeanMapper mapper = (DozerBeanMapper) SpringBeanFactory
								.getBean("beanMapper");
						mapper.map(osConsultation, osContract);
						osContract.setConsultant(new Employee(osConsultation.getConsultant().getId()));
						if(osConsultation.getInterman() != null) {
							osContract.setInterman(new Interman(osConsultation.getInterman().getId()));
						}
						osContract.setCountryIntent(new Country(osConsultation.getCountryIntent().getId()));
						if(osConsultation.getCountryIntent1()!=null) {
							osContract.setCountryIntent1(new Country(osConsultation.getCountryIntent1().getId()));
						}
						if(osConsultation.getCountryIntent2()!=null) {
							osContract.setCountryIntent2(new Country(osConsultation.getCountryIntent2().getId()));
						}
						if(osConsultation.getCountryIntent3()!=null) {
							osContract.setCountryIntent3(new Country(osConsultation.getCountryIntent3().getId()));
						}
						try {
							osContract.setSignupDate(dateFormat.parse(txtSignDate.getText()));
							osContract.setUpdateDate(new Date());
						} catch (ParseException e) {
							e.printStackTrace();
						}
						if (StringUtils.isNotEmpty(txtCommuTranslateSum.getText()))
							osContract.setCommuTranslateSum(new BigDecimal(txtCommuTranslateSum.getText()));
						else
							osContract.setCommuTranslateSum(null);
						osContract.setSignupSum(new BigDecimal(txtSignSum.getText()));
						osContract.setContractNo(txtContractNo.getText());
						osContract.setState(OsContractState.SIGNED);
						Serializable id = osContractService.save(osContract);
						OsConsultationService osConsultationService = (OsConsultationService) SpringBeanFactory
								.getBean("osConsultationService");
						osConsultation.setState(OsConsultationState.SIGNED);
						osConsultationService.update(osConsultation);
						
						MessageDialog.openInformation(getShell(),
								IMessageKeys.SUCCESS, "签约成功！档案编号为" + id);
					} catch (Exception ex) {
						MessageDialog.openError(getShell(), IMessageKeys.FAIL,
								ex.getMessage());
					}	
				}
			} else {
				return;
			}
		}
		super.buttonPressed(buttonId);
	}

}
